package com.dongnam.quanly.web.danhmuc.khohang;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.KhoHangController;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.KhoHang;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "KhoHangBean")
@SessionScoped
public class KhoHangBean implements Serializable {

	private static final Logger logger = LoggerFactory.getLogger(KhoHangBean.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;
	private KhoHangModel khoHangModel;

	// for add KhoHang
	private KhoHang khoHang;
	private boolean isEdit = false;
	// for download file
	private StreamedContent file;

	// for load danh sach phong ban
	private KhoHangController khoHangController;
	private List<KhoHang> listKhoHang;

	// for edit phongBan
	private KhoHang selectedKhoHang;

	public KhoHangBean() {
		super();
		khoHang = new KhoHang();
		loadkhoHang();
		// TODO Auto-generated constructor stub
	}

	public KhoHangController getkhoHangController() {

		if (khoHangController == null)
			khoHangController = new KhoHangController();
		return khoHangController;
	}

	public void setkhoHangController(KhoHangController khoHangController) {
		this.khoHangController = khoHangController;
	}

	public void downloadFileCSV() {

		File excelfile = new File("KHO_HANG.xls");
		List<KhoHang> list = getkhoHangController().findAll();
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);

			sheet.addCell(new Label(0, 0, "Mã Kho Hàng", titleformat));
			sheet.addCell(new Label(1, 0, "Tên Kho Hàng", titleformat));
			sheet.addCell(new Label(2, 0, "Diễn Giải", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getMaKhoHang(), contentformat));
				sheet.addCell(new Label(1, i + 1, list.get(i).getTenKhoHang(), contentformat));
				sheet.addCell(new Label(2, i + 1, list.get(i).getDienGiai(), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "KHO_HANG.xls",
					"UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void handleFileUpload(FileUploadEvent event) {
		logger.debug("process upload file ");
		Workbook w;
		boolean rollback = false;
		List<KhoHang> list = new ArrayList<KhoHang>();
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

			for (int row = 1; row < sheet.getRows(); row++) {

				logger.debug("row " + row);
				Cell cell_ma = sheet.getCell(0, row);
				Cell cell_ten = sheet.getCell(1, row);
				Cell cell_dienGiai = sheet.getCell(2, row);

				KhoHang kh = new KhoHang();
				kh.setMaKhoHang(cell_ma.getContents());
				kh.setTenKhoHang(cell_ten.getContents());
				kh.setDienGiai(cell_dienGiai.getContents());
				list.add(kh);
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		if (!rollback) {
			getkhoHangController().batchSaveOrUpdate(list);
		}

		loadkhoHang();
	}

	public void resetFormAdd() {
		khoHang = new KhoHang();
	}

	public void notifyAdd() {
		isEdit = false;
		resetFormAdd();
	}

	public void notifyEdit(KhoHang khoHang) {
		isEdit = true;
		this.selectedKhoHang = khoHang;
		this.khoHang.fillkhoHang(khoHang);
	}

	public void removeKhoHang() {

		if (this.selectedKhoHang != null) {
			getkhoHangController().makeTransient(this.selectedKhoHang);
			loadkhoHang();
			listKhoHang = getkhoHangController().findAll();
		}

	}

	public void save() {

		RequestContext context = RequestContext.getCurrentInstance();
		try {
			if (isEdit) {
				logger.debug("Edit new KhoHang");

				if (this.selectedKhoHang != null) {

					getkhoHangController().makeTransient(this.selectedKhoHang);

					this.selectedKhoHang.fillkhoHang(this.khoHang);
					this.selectedKhoHang.setUpdateBy(userBean.getUser().getUserId());

					getkhoHangController().makePersistent(this.selectedKhoHang);
					// change state of parent
					context.addCallbackParam("opSuccess", true);
				}

			} else {

				logger.debug("Add new KhoHang :" + this.khoHang.getMaKhoHang());
				KhoHang khoHang = new KhoHang();
				khoHang.setCreateBy(userBean.getUser().getUserId());
				khoHang.setUpdateBy(userBean.getUser().getUserId());

				khoHang.fillkhoHang(this.khoHang);

				getkhoHangController().makePersistent(khoHang);
				listKhoHang = getkhoHangController().findAll();
				context.addCallbackParam("opSuccess", true);

			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			logger.debug("Database error" + e.getMessage());
			context.addCallbackParam("opSuccess", false);

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		loadkhoHang();

	}

	public void loadkhoHang() {
		if (khoHangModel == null)
			khoHangModel = new KhoHangModel();

		khoHangModel.init();
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public void reloadPage() {
		loadkhoHang();
		WebUtil.redirect("/pages/danhmuc/kho.xhtml");
	}

	public KhoHangModel getkhoHangModel() {
		return khoHangModel;
	}

	public void setkhoHangModel(KhoHangModel khoHangModel) {
		this.khoHangModel = khoHangModel;
	}

	public KhoHang getkhoHang() {
		return khoHang;
	}

	public void setkhoHang(KhoHang khoHang) {
		this.khoHang = khoHang;
	}

	public boolean isEdit() {
		return isEdit;
	}

	public void setEdit(boolean isEdit) {
		this.isEdit = isEdit;
	}

	public KhoHangModel getKhoHangModel() {
		return khoHangModel;
	}

	public void setKhoHangModel(KhoHangModel khoHangModel) {
		this.khoHangModel = khoHangModel;
	}

	public KhoHang getKhoHang() {
		return khoHang;
	}

	public void setKhoHang(KhoHang khoHang) {
		this.khoHang = khoHang;
	}

	public List<KhoHang> getListKhoHang() {
		if (listKhoHang == null) {
			listKhoHang = getkhoHangController().findAll();
		}
		return listKhoHang;
	}

	public void setListKhoHang(List<KhoHang> listKhoHang) {
		this.listKhoHang = listKhoHang;
	}

	public KhoHang getSelectedKhoHang() {
		return selectedKhoHang;
	}

	public void setSelectedKhoHang(KhoHang selectedKhoHang) {
		this.selectedKhoHang = selectedKhoHang;
	}

}
